let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
class Controller extends BaseController {
    constructor() {
        super();
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/04技术指标/买入信号/`;
        this.encode = 'UTF-8'
        this.params = {
            pageIndex: 1,
            pageTotal: ''
        }
        this.data = []
    };
    /**
     * 获取url
     */
    getUrl(options) {
        return `http://www.iwencai.com/stockpick/cache?token=${this.params.token}&p=${this.params.pageIndex}0&perpage=30&showType=[%22%22,%22%22,%22onTable%22,%22onTable%22,%22onTable%22,%22onTable%22,%22onTable%22]`
    }

    async getParams() {
        let self = this;
        //获取token

        // await this.page.goto(`http://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=3&qs=result_original&selfsectsn=&querytype=stock&searchfilter=&tid=stockpick&w=%E4%B9%B0%E5%85%A5%E4%BF%A1%E5%8F%B7&queryarea=`)
        // await this.page.waitForSelector('#tableWrap')
        // let data = await this.page.evaluate(function () {
        //     return { pageTotal: parseInt(allResult.total / 30), token: allResult.token }
        // })
        // this.params.token = data.token
        // if (!this.params.pageTotal) {
        //     this.params.pageTotal = data.pageTotal;
        // }

        // //获取列表数据
        // let result = await this.getData({ type: 'list' }, false, 'get')
        // let arr = result.data.result
        // this.codeList = arr || [];
        // this.params.topageTotaltal = parseInt(result.data.total / 30)
        let resultArr = []
        await this.page.goto(`http://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=3&qs=result_original&selfsectsn=&querytype=stock&searchfilter=&tid=stockpick&w=%E4%B9%B0%E5%85%A5%E4%BF%A1%E5%8F%B7&queryarea=`)
        await this.page.waitForSelector('#tableWrap')
        await this.sleep(2000)
        let data = await this.page.evaluate(function () {
            return allResult.result;
        })
        resultArr.push(...data)
        let index = 0;
        function getPage() {
            return new Promise((resolve, reject) => {
                async function get() {
                    await self.page.addScriptTag({
                        content: `
                        $('.atomic_table_con').remove();
                        $('.num.current').next().trigger('click')
                        `
                    })
                    await self.page.waitForSelector('.atomic_table_con')
                    let data = await self.page.evaluate(function () {
                        return allResult.result;
                    })
                    resultArr.push(...data)
                    let length = await self.page.evaluate(function () {
                        return $('.num.current').next().length;
                    })
                    if (length && index < 20) {
                        index++
                        await get()

                    } else {
                        resolve()
                    }
                }
                get()
            })
        }
        await getPage();
        this.codeList = resultArr
    };


    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('99买入信号Controller')
        try {
            for (let i = 0; i < this.codeList.length; i++) {
                let code = this.codeList[i][0].match(/^\d+/)[0];
                this.params.code = code
                this.params.i = i;
                console.log(this.params)
                let url = `http://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=1&qs=index_rewrite&selfsectsn=&querytype=&searchfilter=&tid=stockpick&w=${code}+%E9%80%89%E8%82%A1%E6%96%B0%E5%8A%A8%E5%90%91`
                await this.page.goto(url)
                await this.page.waitForSelector('#dp_block_0')
                let data = await this.page.evaluate(function () {
                    let 动向TagArr = [];
                    $('#tag_cloud_event a').map((i, a) => {
                        动向TagArr.push($(a).text().trim())
                    })
                    let 技术形态Obj = {
                        周: [],
                        日: [],
                        月: []
                    }
                    $('#tag_cloud_zxst a').map((i, a) => {
                        if ($(a).attr('tag').indexOf('月') > -1) {
                            技术形态Obj['月'].push($(a).text().trim())
                        } else if ($(a).attr('tag').indexOf('周') > -1) {
                            技术形态Obj['周'].push($(a).text().trim())
                        } else {
                            技术形态Obj['日'].push($(a).text().trim())
                        }
                    })

                    let 买入信息Obj = {
                        周: [],
                        日: [],
                        月: []
                    }
                    $('#tag_cloud_buy a').map((i, a) => {
                        if ($(a).attr('tag').indexOf('月') > -1) {
                            买入信息Obj['月'].push($(a).text().trim())
                        } else if ($(a).attr('tag').indexOf('周') > -1) {
                            买入信息Obj['周'].push($(a).text().trim())
                        } else {
                            买入信息Obj['日'].push($(a).text().trim())
                        }
                    })

                    let 主力动向分析 = {}
                    $('span:contains(主力动向分析)').parents('.dp_nestedblocks_block_con').find('.btc_s_title').map((i, e) => {
                        主力动向分析[$(e).text().trim()] = $(e).next().text().trim()
                    })

                    let 筹码分析 = {}
                    $('span:contains(筹码分析)').parents('.dp_nestedblocks_block_con').find('.btc_s_title').map((i, e) => {
                        筹码分析[$(e).text().trim()] = $(e).next().text().trim()
                    })
                    return { 动向TagArr, 技术形态Obj, 买入信息Obj, 主力动向分析, 筹码分析 }
                })
                data.code = code
                this.data.push(data)
            }
        } catch (err) {
            console.log(err)
            await this.getHistory()
        }
    };


    /**
     * 写csv
     */
    writeCsv(arr) {

        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        if (arr && arr.length) {
            fs.writeFileSync(path.join(this.baseSrc, `买入信号_${new Date().format('yyyyMMdd')}.csv`), this.convertToCSV(arr, 'title'), 'UTF-8')
        }
    }

    outputDataFormat(arr) {
        let newArr = []
        arr.map(item => {
            let code = item.code;
            let 动向 = item.动向TagArr.join(',')
            let 技术形态_周 = item.技术形态Obj.周.join(',');
            let 技术形态_月 = item.技术形态Obj.月.join(',');
            let 技术形态_日 = item.技术形态Obj.日.join(',');
            let 买入信息_周 = item.买入信息Obj.周.join(',');
            let 买入信息_月 = item.买入信息Obj.月.join(',');
            let 买入信息_日 = item.买入信息Obj.日.join(',');
            let 主力动向分析 = ''
            for (let key in item.主力动向分析) {
                主力动向分析 += `${key}:${item.主力动向分析[key]};`
            }

            let 筹码分析 = ''
            for (let key in item.筹码分析) {
                筹码分析 += `${key}:${item.筹码分析[key]};`
            }
            let obj = { code, 动向, 技术形态_周, 技术形态_月, 技术形态_日, 买入信息_周, 买入信息_月, 买入信息_日, 主力动向分析, 筹码分析 }
            newArr.push(obj)
        })
        return newArr
    }

    async main(startDate = '2015-01-01', isCache = true) {this.startDate = startDate;this.isCache = isCache;

        await this.initPuppeteer({ headless: false })
        await this.getParams()
        await this.getHistory()
        await this.writeCsv(this.data)
        await this.browser.close();
    }
}

let controller = new Controller()
controller.main();

// module.exports = controller